import { Next, Context } from 'koa';
import mongoose, { type Mongoose } from 'mongoose';

const host = process.env.DB_HOST;
const port = process.env.DB_PORT;

export const dbConfig = {
  user: process.env.DB_ACCOUNT,
  pass: process.env.DB_PASSWORD,
  dbName: process.env.DB_NAME
}

export const dbConnect = () => {
  let db: Mongoose;
  let hooks: Function[] = [];

  const connectSuccess = () => {
    console.log('请求数据库成功...');
    hooks.forEach(hook => hook());
    hooks = [];
  }

  const createConnect = async () => {
    const uri = `mongodb://${host}:${port}`;
    db = await mongoose.connect(uri, dbConfig);
    connectSuccess();
  }

  return async (_: Context, next: Next) => {
    if (!db) await new Promise((resolve) => {
      hooks.push(resolve);
      if (hooks.length == 1) createConnect();
    });
    await next();
  }
}